package com.saoft.fangcms.generator.preview;

import com.baomidou.mybatisplus.generator.config.ConstVal;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

@Component
public class FreemarkerStringComponent {

    private Configuration configuration;

    public FreemarkerStringComponent() {
        this.configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        this.configuration.setDefaultEncoding(ConstVal.UTF8);
        this.configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, "/");
    }

    /**
     * 生成字符串
     * @param data
     * @param templateFile
     * @return
     */
    public String generatorString(Map<String,Object> data,String templateFile){
        try {
            Template template = configuration.getTemplate(templateFile+".ftl");
            StringWriter writer= new StringWriter();
            template.process(data,writer);
            return writer.getBuffer().toString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return null;
    }
}
